/**
 * 常用方法： 包括读取json，查询json等
 * Created by mlr on 2016/9/6.
 */
var path = require('path')
    ,   fs = require('fs')
    ,   config = require('config')
    ,   errMsg = config.get("SYS.errMsg")
    ,   DATA_PATH = config.get("DATA_PATH")
    ,   FILE_DIR = config.get('SYS.upload.dirName');

var chars = ['0','1','2','3','4','5','6','7','8','9',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S',
    'T','U','V','W','X','Y','Z',
    'a','b','c','d','e','f','g','h','i','j','k','l','h','n','o','p','q','r','s',
    't','u','v','w','x','y','z'];

exports = module.exports = {
    random: function(n) {
        var res = "";
        !n && (n = 32);
        for(var i = 0; i < n ; i ++) {
            var id = Math.ceil(Math.random()*59);
            res += chars[id];
        }
        return res;
    },
    checkData: function() {
        fs.exists(DATA_PATH, function(exists) {
            if(!exists) {
                if (!fs.existsSync(path.join(__dirname, 'routes/data'))) {
                    fs.mkdirSync(path.join(__dirname, 'routes/data'));
                }
                fs.appendFileSync(DATA_PATH, String(JSON.stringify({count: 0, list:[]})));
            }
        });
    },
    getData: function(isCheck) {
        if (isCheck){
            this.checkData();
        }
        var data = fs.readFileSync(DATA_PATH, "utf-8") || {count: 0, list:[]};
        if (!data) {
            fs.appendFileSync(DATA_PATH, String(JSON.stringify(data)));
        } else {
            data = JSON.parse(data);
        }
        return data;
    },
    getNowTime: function() {
        var curDate = new Date();
        var curTime = curDate.getFullYear() + '-' + (curDate.getMonth()+1 ) + '-' + curDate.getDate() + ' ';
        curTime += curDate.getHours() + ':' + curDate.getMinutes() + ':' + curDate.getSeconds();
        return curTime;
    },
    appendData: function(data){
        try {
            this.checkData();
            if (!data) {
                return errMsg.base['POST_EMPTY'];
            }
            data._id = this.random(32);
            data.createTime = this.getNowTime();
            data.updateTime = this.getNowTime();
            var _data = this.getData();
            _data.list.push(data);
            _data.count++;
            fs.writeFileSync(DATA_PATH, JSON.stringify(_data), {'encoding': 'utf8'});
            return {err:0, _id: data._id};
        } catch(e) {
            console.log(e);
            return errMsg.base['DB_EXPETION'];
        }
    },
    modifyData: function(data) {
        try {
            this.checkData();
            data.updateTime = this.getNowTime();
            var _data = this.getData();
            var _data_list = _data.list;
            if (parseInt(_data.count) == 0 || _data_list.length == 0) {
                return {err:0};
            }
            for (var i = 0; i < _data_list.length; i++) {
                var cur_person = _data_list[i];
                if (cur_person._id == data._id) {
                    _data_list[i] = data;
                }
            }
            fs.writeFileSync(DATA_PATH, JSON.stringify(_data), {'encoding': 'utf8'});
            return {err:0};
        } catch(e){
            console.log(e);
            return errMsg.base['DB_EXPETION'];
        }
    },
    delData: function(_id) {
        try {
            this.checkData();
            var _data = this.getData();
            var _data_list = _data.list;
            if (parseInt(_data.count) == 0 || _data_list.length == 0) {
                return {err:0};
            }
            for (var i = 0; i < _data_list.length; i++) {
                var cur_person = _data_list[i];
                if (cur_person._id == _id) {
                    _data_list.splice(i, 1);
                    var filePath = path.join(FILE_DIR, cur_person.appName, cur_person.fileName);
                    if (fs.existsSync(filePath)) {
                        fs.unlinkSync(filePath);
                    }
                }
            }
            _data.count--;
            fs.writeFileSync(DATA_PATH, JSON.stringify(_data), {'encoding': 'utf8'});
            // 删除文件

            return {err:0};
        } catch(e){
            console.log(e);
            return errMsg.base['DB_EXPETION'];
        }
    },
    findById: function(_id) {
        try {
            this.checkData();
            var _data = this.getData();
            var _data_list = _data.list;
            if (parseInt(_data.count) == 0 || _data_list.length == 0) {
                return null;
            }
            for (var i = 0; i < _data_list.length; i++) {
                var cur_person = _data_list[i];
                if (cur_person._id == _id) {
                    return cur_person;
                }
            }
            return null;
        } catch(e){
            console.log(e);
            return errMsg.base['DB_EXPETION'];
        }
    }
};
